//路由鉴权:鉴权,项目当中路由能不能被的权限的设置(某一个路由什么条件下可以访问、什么条件下不可以访问)
import router from '@/router/index.ts';
import nprogress from 'nprogress';
import pinia from './store';
import setting from './setting';
//引入进度条样式
import "nprogress/nprogress.css";
nprogress.configure({ showSpinner: false });
import loginStore from './store/modules/login';
// 动态路由
import { watch } from 'vue';
let userStore = loginStore(pinia)
import { ref } from 'vue';
// 定义标识，记录路由是否添加
const hasRoles = ref(true)


router.beforeEach(async (to: any, from: any, next: any) => {
    console.log(to, '全局守卫数据');

    document.title = `${setting.title} - ${to.meta.title}`
    //to:你将要访问那个路由
    //from:你从来个路由而来
    //next:路由的放行函数
    // console.log('王世彪进来了');
    nprogress.start();
    let token = userStore.token
    let username = userStore.username
    if (token) {
        if (to.path == '/Login') {

            next({ path: '/' })
        } else {
            username = ""
            if (username) {
                //  放行
                next()
            } else {
                try {
                    if (hasRoles.value) {
                        await userStore.userInfo();
                        hasRoles.value = false;
                        next(`${to.path}`)
                    } else {
                        next()
                    }


                } catch (error) {
                    await userStore.userLoginOut()
                    next({ path: '/login', query: { redirect: to.path } })
                }
            }
        }
    } else {
        if (to.path == '/login') {
            next()
        } else {
            next({ path: '/login', query: { redirect: to.path } });
        }
    }

})

//全局后置守卫
router.afterEach((to: any, from: any) => {
    // console.log('王世彪出去了');
    nprogress.done();
});